package demo;

import java.util.PriorityQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 苏李涛
 * Date: 2024-10-22
 * Time: 17:24
 */

/**
 * 自己模拟实现定时器：
 */

class MyTimerTask implements Comparable<MyTimerTask>{
    private Runnable task;
    private long time;// 记录任务要执行的时刻

    MyTimerTask(Runnable task,long time){
        this.task = task;
        this.time = time;

    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int) (this.time - o.time);
    }

    //返回任务要执行的时刻
    public long getTime(){
        return time;
    }

    public void run(){
        task.run();
    }
}

//自己创建的定时器
class MyTimer{
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();
    private Object locker = new Object();

    public void schedule(Runnable task,long delay){

        synchronized (locker) {
            // 以入队列这个时刻作为时间基准.
            MyTimerTask timerTask = new MyTimerTask(task, System.currentTimeMillis() + delay);
            queue.offer(timerTask);
            locker.notify();
        }
    }

    // 创建一个线程, 负责执行队列中的任务
    MyTimer(){

        Thread t = new Thread(()->{
            try {
                synchronized (locker) {
                    while (true) {
                        while (queue.isEmpty()) {
                            // 这里的 sleep 时间不好设定!!
                            locker.wait();
                        }

                        MyTimerTask task = queue.peek();
                        if (System.currentTimeMillis() < task.getTime()) {
                            //系统时间小于任务要执行的时间->还未到执行任务的时候
                            locker.wait(task.getTime() - System.currentTimeMillis());
                        } else {

                            task.run();//线程执行任务
                            queue.poll();
                        }
                    }
                }

            }catch (InterruptedException e){
                e.printStackTrace();
            }
        });

        t.start();
    }
}
public class Demo2 {
    public static void main(String[] args) {
        MyTimer timer = new MyTimer();
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 1000");
            }
        },1000);

        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 2000");
            }
        },2000);

        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 3000");
            }
        },3000);
    }
}
